package com.gollum.common.utils.ip;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.gollum.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;


/**
 * 获取地址功能类
 *
 * @auther: Herther
 * @version 1.0.0
 * @date: 2022/9/4 22:47
 */
public class AddressUtils
{
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    /** IP地址查询 **/
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    /**  未知地址 **/
    public static final String UNKNOWN = "UNKNOWN";

    public static String getRealAddressByIP(String ip) {
        try {
            HashMap<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("ip", ip);
            paramsMap.put("json", true);
            String rspStr = HttpUtil.get(IP_URL, paramsMap);
            if (StringUtils.isEmpty(rspStr)) {
                log.error("获取地理位置异常 {}", ip);
                return UNKNOWN;
            }
            JSONObject obj = JSON.parseObject(rspStr);
            String region = obj.getString("pro");

            if (StringUtils.isEmpty(region)){
                log.error("获取地理位置异常 {}", ip);
                String addr = obj.getString("addr");
                if (StringUtils.isEmpty(addr)){
                    return UNKNOWN;
                }
                return addr;
            }

            String city = obj.getString("city");
            return String.format("%s %s", region, city);
        }
        catch (Exception e)
        {
            log.error("获取地理位置异常 {}", ip);
        }
        return UNKNOWN;
    }

}
